package com.email.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：hanll
 * ClassName：QRCodeTest
 * Date：2022/10/5 12:48
 * Version：1.0
 * Description：二维码生成
 */
public class QRCodeTest {

    private static final String QR_CODE_IMAGE_PATH = "C:\\Users\\l\\Desktop\\qrCode.jpg";

    private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        Map<EncodeHintType, Object> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, map);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "JPG", path);

    }
    public static void main(String[] args) {
        try {
            generateQRCodeImage("臭宝啵啵啵，耐你❤", 350, 350, QR_CODE_IMAGE_PATH);
            System.out.println("生成成功!");
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }
    }
}
